import axios from 'axios'
import Taro from '@tarojs/taro'
import { SERVICE_URL_V1 } from "@/config/config"
import { toUserLoginPage } from "@/utils/page_router"
import { getGlobalData, getUserTokenStorage, setGlobalData, getSourceId , setSourceId } from "@/utils/storage"
import { AUTH_TOKEN } from "@/config/storage";

// 创建 axios 实例
const request = axios.create({
  // API 请求的默认前缀
  baseURL: SERVICE_URL_V1,
  timeout: 6000 // 请求超时时间
})

// 异常拦截处理器
const errorHandler = (error) => {
  if (error.response) {
    const { config, data, status } = error.response
    const { isAuth = true } = config
    switch (status) {
      case 401:
        // //  避免重复跳转登录
        // if (isAuth && !getGlobalData('verifyLoginPage')) {
        //   setGlobalData({ verifyLoginPage: true })
        //   // toUserLoginPage()
        // }
        break
      default:
        Taro.hideLoading()
        Taro.showToast({ icon: 'none', title: data.message })
    }
  }
  return Promise.reject(error)
}

// request interceptor
request.interceptors.request.use(config => {
  // const token = Taro.getStorageSync(AUTH_TOKEN)
  const token = getUserTokenStorage()
  // 如果 token 存在
  // 让每个请求携带自定义 token 请根据实际情况自行修改
  if (token) {
    config.headers['Access-Token'] = token
  }
  let url = window.location.href;
  let sourceId = '';
  if (url.indexOf('?') != -1) {
    var temp1 = url.split('?');
    var pram = temp1[1];
    var keyValue = pram.split('&');
    var obj = {};
    for (var i = 0; i < keyValue.length; i++) {
      var item = keyValue[i].split('=');
      var key = item[0];
      var value = item[1];
      obj[key] = value;
    }
    for (var key in obj) {
      if (key == 'sourceId') {
        sourceId = obj[key]
        setSourceId({ sourceId: sourceId })
      }
    }
  }
  let sourceIddata = getSourceId();
  let realSourceId = sourceIddata.sourceId;

  if (realSourceId) {
    if (config.method == 'get') {
      config.params = {
        ...config.params,
        sourceId:realSourceId
      }
    } else if (config.method == 'post' || config.method == 'put') {
      config.data = {
        ...config.params,
        sourceId:realSourceId
      }
    }
  }
  return config
}, errorHandler)

// response interceptor
request.interceptors.response.use((response) => {
  return response.data
}, errorHandler)

export default request
